<?php


namespace App\Services;

use App\Models\Company;
use App\Models\DriverRecordLog;
use App\Models\DriverWallets;
use App\Models\User;
use App\Models\VerificationCode;
use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class UsersService extends BaseService
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 退出登录
     */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return true;
    }

    public static function details(User $user)
    {
        return response()->json(['success' => $user]);
    }

    /**
     * 设置密码
     */
    public function password_confirmed($data)
    {
        $user = Auth::user();
        $data = [
            'password' => password_hash($data['password'], PASSWORD_BCRYPT),
            'avatar' => $data['avatar'] ? $data['avatar'] : '',
            'name' => $data['name'] ? $data['name'] : ''
        ];
        $rest = User::query()->where('id', $user->id)->update($data);
        return $rest ? true : false;
    }

    /**
     * @param $user
     * @return mixed
     * 获取司机ID
     */
    public static function driver_id(User $user)
    {
        return $user->driver()->first() ? $user->driver()->first()->id : 0;
    }

    /**
     * 密码检测
     */
    public function password_check(User $user)
    {
        $res = DriversService::status($user);
        $res['type'] = $user->password ? 1 : 0;
        return $res;
    }

    /**
     * 密码修改
     */
    public function ChangePassword(array $data)
    {
        $user = Auth::user();
        if (!password_verify($data['password1'], $user->password)) {
            return_bob('原密码不正确,请重新输入');
        }
        $data = [
            'password' => password_hash($data['password'], PASSWORD_BCRYPT),
        ];
        return User::query()->where('id', $user->id)->update($data);
    }

    /**
     * @param User $user
     * @return array
     * 用户信息
     */
    public function user_info(User $user)
    {
        $company_id = $user->driver()->first() ? $user->driver()->first()->company_id : '';
        $real_name = $user->driver()->first() ? $user->driver()->first()->real_name : '';
        $name = Company::query()->where('id', $company_id)->first('name');
        $data = [
            'name' => $user->name ? $user->name : $real_name,
            'phone' => $user->phone,
            'avatar' => $user->avatar,
            'sex' => $user->sex,
            'company_id' => $company_id,
            'company_name' => $name ? $name->name : '',
        ];
        return $data;
    }

    /**
     * 司机钱包
     */
    public function wallet_count(string $type)
    {

        $driver_id = $this->driver_id(Auth::user());
        self::Judgment_to_be_settled($driver_id);
        $wallet = DriverWallets::query()->where('driver_id', $driver_id)->where('type', $type)->first(['amount', 'settled_amount', 'balance']);
        if (!$wallet) {
            $wallet = [
                'amount' => 0,
                'settled_amount' => 0,
                'balance' => 0,
            ];
        }
        return $wallet;
    }

    /**
     * 待结算资金判断
     */
    public function Judgment_to_be_settled(int $driver_id)
    {
        $time = 60 * 60 * 24 * 7;
        $list = DriverRecordLog::query()->where(
            [
                ['set_type', '2'],
                ['status', '1'],
                ['driver_id', $driver_id],
            ])->get();
        if ($list) {
            foreach ($list as $key => $value) {
                $times = strtotime($value['created_at']) + $time;
                if ($times <= time()) {
                    DB::transaction(function () use ($value) {
                        DriverRecordLog::query()->where('id', $value['id'])->update(['status' => '2', 'end_time' => Carbon::now(), 'note' => '自动结算']);
                        DriverWallets::query()->where('driver_id', $value['driver_id'])->where('type', $value['rules'])->update([
                            'settled_amount' => DB::raw('settled_amount - ' . $value['money']),  //待结算减去结算的钱到可提现里面去
                            'amount' => DB::raw('amount + ' . $value['money']), //可提现
                        ]);
                    });
                }
            }
        }
    }

    /**
     * 提现明细
     */
    public function wallet_list(User $user, $startOfMonth, $endOfMonth, $type, $page, $size)
    {
        $where = [];
        if ($type) {
            $where = ['set_type' => $type];
        }
        $driver_id = $user->driver()->first() ? $user->driver()->first()->id : 0;
        $info = DriverRecordLog::query()
            ->where('driver_id', $driver_id)
            ->where($where)
            ->orderByDesc('id')
            ->forPage($page, $size)
            ->whereBetween('created_at', [$startOfMonth, $endOfMonth])
            ->get(['id', 'name', 'money', 'stard_time', 'end_time', 'status', 'type', 'set_type', 'created_at', 'in_type']);
        $setmoney = $this->wallet_list_count($startOfMonth, $endOfMonth, $driver_id, 1); //收入
        $getmoney = $this->wallet_list_count($startOfMonth, $endOfMonth, $driver_id, 2);  //转出
        return compact('info', 'setmoney', 'getmoney');
    }

    /**
     * @param User $user
     * 提现/结算详情
     */
    public function driver_wallet_details(int $id)
    {
        return DriverRecordLog::query()->where('id', $id)->first();
    }

    /**
     * 本月收入 / 转出
     */
    public function wallet_list_count($startOfMonth, $endOfMonth, $driver_id, $set_type)
    {
        $data = DriverRecordLog::select()
            ->where('driver_id', '=', $driver_id)
            ->where('set_type', $set_type)
            ->whereBetween('created_at', [$startOfMonth, $endOfMonth])
            ->sum('money');
        return $data;
    }

    /**
     * 忘记密码
     */
    public function Forget_password(string $phone, string $code, string $pwd)
    {
        try {
            $user = User::query()->where('phone', $phone)->first();
            if (!$user) return_bobc('用户不存在');
            $code_info = VerificationCode::query()->where('channel', 'sms')->where('account', $phone)->orderByDesc('created_at')->first();
            if (!$code_info || $code_info->state == 1 || $code_info->code != $code) {
                return_bobc('验证码有误');
            }
            $code_info->state = 1;
            $code_info->save();
            $user->password = password_hash($pwd, PASSWORD_BCRYPT);
            $user->save();

        } catch (QueryException $exception) {
            return $exception;
        }
        return true;
    }
}
